import java.io.IOException;
import java.util.Iterator;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hit;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.store.FSDirectory;

public class Lucene_2 {
	private static final String INDEX_DIRECTORY = "indexDirectory";
	public static final String FIELD_PATH = "path";

	public static void buildIndex() throws IOException {
		IndexWriter indexWriter = new IndexWriter(FSDirectory.getDirectory(INDEX_DIRECTORY), new StandardAnalyzer(), true);
		String[] texts = new String[] { "hello world", "hello sailor", "goodnight moon" };
		System.out.println("creating index");
		int i=1;
		for (String text : texts) {
			Document doc = new Document();
			doc.add(new Field("text", text, Field.Store.YES, Field.Index.TOKENIZED));
			doc.add(new Field("loc", ""+i, Field.Store.YES, Field.Index.TOKENIZED));
			indexWriter.addDocument(doc);
			i++;
		}
		indexWriter.close();
	}

	public static void searchIndex(String[] queryStrings) throws IOException, ParseException {
		Searcher searcher = new IndexSearcher(FSDirectory.getDirectory(INDEX_DIRECTORY));
		QueryParser parser = new QueryParser("text", new StandardAnalyzer());
		for (String queryString : queryStrings) {
			System.out.println("searching for: " + queryString);
			Query query = parser.parse(queryString);
			Hits hits = searcher.search(query);

			System.out.println("Number of hits: " + hits.length());
			Iterator<Hit> it = hits.iterator();
			while (it.hasNext()) {
				Hit hit = it.next();
				Document document = hit.getDocument();
				String originalTxt = document.get("text");
				String loc=document.get("loc");
				System.out.println("Hit: " + originalTxt + " at "+loc);
			}
		}
		searcher.close();
	}

	public static void main(String[] args) throws Exception {
		buildIndex();
		searchIndex(new String[] { "moon", "av" });
	}
}
